package com.fangwaii.core.authorization;

import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;

import java.util.Date;

/**
 * @author lxc18
 * @date 2024/12/6 15:14
 * @description JWT
 */
public class JWTUtil {


    private static final String SECRET = "mySecretKey"; // 密钥
    private static final long EXPIRATION_TIME = 86400000; // 1 天

    // 生成 Token
    public static String generateToken(String id) {
        return Jwts.builder()
                .setSubject(id)
                .setExpiration(new Date(System.currentTimeMillis() + EXPIRATION_TIME))
                .signWith(SignatureAlgorithm.HS256, SECRET)
                .compact();
    }

    // 验证 Token 是否有效
    public static boolean verify(String id, String token) {
        try {
            String subject = Jwts.parser()
                    .setSigningKey(SECRET)
                    .parseClaimsJws(token)
                    .getBody()
                    .getSubject();
            return subject.equals(id);
        } catch (Exception e) {
            return false;
        }
    }

}
